package stdlib

//#include <time.h>
import "C"

//import "os"
import "time"
import . "api"


var sysLib = map[string]GoFunction{
	"clock": osClock,
	"difftime":	osDiffTime,
	"time": osTime,
}


func OpenOSLib(ls LuaState) int {
	ls.NewLib(sysLib)
	return 1
}


// os.clock ()
// http://www.lua.org/manual/5.3/manual.html#pdf-os.clock
// lua-5.3.4/src/loslib.c#os_clock()
func osClock(ls LuaState) int {
	c := float64(C.clock()) / float64(C.CLOCKS_PER_SEC)
	ls.PushNumber(c)
	return 1
}


// os.difftime (t2, t1)
// http://www.lua.org/manual/5.3/manual.html#pdf-os.difftime
// lua-5.3.4/src/loslib.c#os_difftime()
func osDiffTime(ls LuaState) int {
	t2 := ls.CheckInteger(1)
	t1 := ls.CheckInteger(2)
	ls.PushInteger(t2 - t1)
	return 1
}


// os.time ([table])
// http://www.lua.org/manual/5.3/manual.html#pdf-os.time
// lua-5.3.4/src/loslib.c#os_time()
func osTime(ls LuaState) int {
	if ls.IsNoneOrNil(1) {/* called without args? */
		t := time.Now().Unix()	/* get current time */
		ls.PushInteger(t)
	} else {
		ls.CheckType(1, LUA_TTABLE)
		sec := _getField(ls, "sec", 0)
		min := _getField(ls, "min", 0)
		hour := _getField(ls, "hour", 12)
		day := _getField(ls, "day", -1)
		month := _getField(ls, "month", -1)
		year := _getField(ls, "year", -1)
		// todo: isdst
		t := time.Date(year, time.Month(month), day,
			hour, min, sec, 0, time.Local).Unix()
		ls.PushInteger(t)
	}
	return 1
}


// lua-5.3.4/src/loslib.c#getfield()
// dft表示默认值, 如果默认值为-1, 表示必须包含这个字段
// 如果大于0, 表示该字段的默认值
func _getField(ls LuaState, key string, dft int64) int {
	t := ls.GetField(-1, key)	/* get field and its type */
	res, isNum := ls.ToIntegerX(-1)
	if !isNum {	/* field is not an integer? */
		if t != LUA_TNIL {	/* some other value? */
			return ls.Error2("field '%s' is not an integer", key)
		} else if dft < 0 {	/* absent field; no default? */
			return ls.Error2("field '%s' missing in date table", key)
		}
		res = dft
	}
	ls.Pop(1)
	return int(res)
}